/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fatecpg.songs.site.managedbeans;

import br.com.fatecpg.songs.dao.UserDAO;
import br.com.fatecpg.songs.dao.util.DAOException;
import br.com.fatecpg.songs.dao.util.DAOFactory;
import br.com.fatecpg.songs.entity.User;
import br.com.fatecpg.songs.util.Constants;
import br.com.fatecpg.songs.util.FacesContextUtil;
import java.io.Serializable;
import javax.faces.bean.ManagedBean;

import javax.faces.bean.SessionScoped;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Marcos
 */
@ManagedBean
@SessionScoped
public class LoginManagedBean implements Serializable{
    private User user;
    private UserDAO userDAO;
    private static Log log = LogFactory.getLog(DAOFactory.class);
    
    public LoginManagedBean() throws DAOException {        
        user = new User();                  
        userDAO = (UserDAO) DAOFactory.getDAO(User.class);
    }    
    
    public User getUser() {        
        if(!isLogged() && user.getId() != null){
            user = new User();        
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }    
    
    public void login(){
        
        User user = userDAO.login(this.user);  
        if(user != null){            
            this.user = user;            
            FacesContextUtil.putOnSessionMap(Constants.USER_KEY, user);
        }
        
    }
    
    public void logout(){
        try{
            user = new User();
            FacesContextUtil.removeFromSessionMap(Constants.USER_KEY);
            FacesContextUtil.refresh();
        }catch(Exception ex){
            log.error("Erro ao efetuar logout", ex);
        }
    }
    
    public boolean isLogged(){        
        return FacesContextUtil.getFromSessionMap(Constants.USER_KEY) != null;
    }        
}
